package com.ninth_group.interceptor;

import cn.hutool.json.JSONUtil;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.ninth_group.constant.JWTConstants;
import com.ninth_group.result.R;
import com.ninth_group.utils.JWTUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotNull;
import org.springframework.lang.NonNull;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class JWTInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(
            HttpServletRequest request,
            HttpServletResponse response, Object handler)
            throws Exception {
        // 放行OPTIONS请求
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            return true;
        }
        // 从请求头获取 token（推荐方式）
        String token = request.getHeader(JWTConstants.JWT_HEADER_INFO); // 通常是 "Authorization"

        System.out.println("token -> " + token);

        // 如果 header 没有，尝试从 session 获取（可选）
        if (token == null) {
            token = (String) request.getSession().getAttribute(JWTConstants.JWT_HEADER_INFO);
        }

        // 去除 "Bearer " 前缀
        if (token != null && token.startsWith(JWTConstants.TOKEN_PREFIX)) {
            token = token.substring(JWTConstants.TOKEN_PREFIX.length()).trim();
        }

        try {
            if (token == null || token.isEmpty()) {
                throw new RuntimeException("token 丢失");
            }
            JWTUtil.verify(token); // 验证 token
            return true; // 放行
        } catch (SignatureVerificationException e) {
            returnJsonResponse(response, R.unauthorized("签名不匹配"));
        } catch (TokenExpiredException e) {
            returnJsonResponse(response, R.unauthorized("token 已过期"));
        } catch (AlgorithmMismatchException e) {
            returnJsonResponse(response, R.unauthorized( "算法不匹配"));
        } catch (Exception e) {
            returnJsonResponse(response, R.unauthorized("token 无效"));
        }
        return false; // 拦截请求
    }

    // 返回 JSON 响应
    private void returnJsonResponse(HttpServletResponse response, R r) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 401
        response.getWriter().println(JSONUtil.toJsonStr(r));
    }
}
